package com.block.datapush.service.apipush;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.block.common.constant.RedisKeyConstant;
import com.block.common.enums.BaseTypeInfoEnum;
import com.block.common.model.param.PushApiKeyParam;
import com.block.common.service.IMemberCommonService;
import com.block.common.service.LogFactory;
import com.block.datapush.enums.PushStatusEnum;
import com.block.datapush.model.PushQueryParam;
import com.block.datapush.model.dto.NoticeParamDTO;
import com.block.datapush.model.result.ProtocolParamResult;
import com.block.datapush.model.result.PushApiResult;
import com.block.datapush.service.IPushApiService;
import com.block.datapush.service.apipush.utils.WangLuoKeJiUtil;
import com.block.db.entity.MemberSourceInfo;
import com.block.db.entity.MerchantBaseInfo;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 新鼎鑫金服
 */
@Service
public class XinDingXinJinFuApiService implements IPushApiService {

    private static final Logger log = LogFactory.getPushLog();

    private static final int TOKEN_EXPIRY_MINUTES = 90;

    @Autowired
    IMemberCommonService memberCommonService;


    @Override
    public PushApiResult checkUser(String orderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) {

        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);


        String queryUrl = pushApiKeyParam.getCheckUrl();

        String token = getToken(pushApiKeyParam.getApiKey(), pushApiKeyParam.getApiSecret(), pushApiKeyParam.getInfoId(), pushApiKeyParam.getQueryUrl());


        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("accessID", pushApiKeyParam.getApiKey());
        paramMap.put("token", token);
        paramMap.put("Phone", memberSourceInfo.getMobileMd5());



        log.info("【新鼎鑫金服】撞库开始【queryUrl】{}【paramMap】{}", queryUrl, JSON.toJSONString(paramMap));
        String result = HttpUtil.createPost(queryUrl).body(JSON.toJSONString(paramMap)).execute().body();
        log.info("【新鼎鑫金服】撞库结束【result】{}", result);

        JSONObject resultObject = JSON.parseObject(result);
        log.info("撞库结果resultObject : {}", resultObject);
        String orsuccess = resultObject.getString("orsuccess");
        String Msg = resultObject.getString("Msg");

        pushApiResult.setCode(orsuccess + "|");
        pushApiResult.setMessage(Msg);
        pushApiResult.setParamInfo(JSON.toJSONString(paramMap));
        pushApiResult.setResultInfo(result);

        if (StrUtil.equals(String.valueOf(orsuccess), "1")) {
            pushApiResult.setPushSuccess(true);
        }
        return pushApiResult;
    }

    @Override
    public PushApiResult queryApprove(String orderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) {
        return null;
    }

    @Override
    public PushApiResult registerUser(String orderNo, String outOrderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) {
        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);
        pushApiResult.setOrderNo(orderNo);

        String requestUrl = pushApiKeyParam.getRegisterUrl();



        String token = getToken(pushApiKeyParam.getApiKey(), pushApiKeyParam.getApiSecret(), pushApiKeyParam.getInfoId(), pushApiKeyParam.getQueryUrl());

        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("accessID", pushApiKeyParam.getApiKey());
        paramMap.put("token", token);
        paramMap.put("F1", memberSourceInfo.getRealname());
        paramMap.put("F2", memberSourceInfo.getMobile());
        paramMap.put("F3", 2);
        paramMap.put("F4", BaseTypeInfoEnum.LoanAmount.getNameByValue(memberSourceInfo.getLoanAmount()));
        paramMap.put("F5", 0);
        paramMap.put("F6", this.getUserInfo(memberSourceInfo));

        log.info("【新鼎鑫金服】导单开始【queryUrl】{}【paramMap】{}", requestUrl, JSON.toJSONString(paramMap));
        String result = HttpUtil.createPost(requestUrl).body(JSON.toJSONString(paramMap)).execute().body();
        log.info("【新鼎鑫金服】导单结束【result】{}", result);

        JSONObject resultObject = JSON.parseObject(result);
        String orsuccess = resultObject.getString("orsuccess");
        String Msg = resultObject.getString("Msg");

        pushApiResult.setCode(orsuccess + "|");
        pushApiResult.setMessage(Msg);
        pushApiResult.setParamInfo(JSON.toJSONString(paramMap));
        pushApiResult.setResultInfo(result);

        if (StrUtil.equals(String.valueOf(orsuccess), "1")) {
            pushApiResult.setPushSuccess(true);
            pushApiResult.setSettleFlag(true);
            pushApiResult.setStatus(PushStatusEnum.SUCCESS.getValue());
            return pushApiResult;
        }
        pushApiResult.setPushSuccess(false);
        pushApiResult.setSettleFlag(false);
        pushApiResult.setStatus(PushStatusEnum.FAILED.getValue());
        return pushApiResult;
    }

    @Override
    public PushApiResult queryResult(PushQueryParam pushQueryParam, PushApiKeyParam pushApiKeyParam, String extJson) {
        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);
        return pushApiResult;
    }


    @Override
    public NoticeParamDTO getNoticeResultParam(String infoId, Map<String, String[]> parameterMap, String paramContent) {
        NoticeParamDTO noticeParamDTO = new NoticeParamDTO();
        return noticeParamDTO;
    }

    @Override
    public JSONObject getNoticeResultReturn(Map<String, String[]> parameterMap, String paramContent, JSONObject extObject) {
        JSONObject jsonObject = new JSONObject();
        return jsonObject;
    }

    @Override
    public ProtocolParamResult getProtocolResult(MerchantBaseInfo merchantBaseInfo, MemberSourceInfo memberSourceInfo) {
        ProtocolParamResult paramResult = new ProtocolParamResult();
        return paramResult;
    }

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    public String getToken(String accessID, String accessKey, String id, String requestUrl) {

        String redisKey = StrUtil.format(RedisKeyConstant.MERCHANT_PUSH_TOKEN_KEY, id);
        String token = stringRedisTemplate.opsForValue().get(redisKey);


        if (token == null || token.isEmpty()) {
            Map<String, String> paramMap = new HashMap<>();
            paramMap.put("accessID", accessID);
            paramMap.put("accessKey", accessKey);

            log.info("【新鼎鑫金服】获取token【queryUrl】{}【paramMap】{}", requestUrl, JSON.toJSONString(paramMap));
            String result = HttpUtil.createPost(requestUrl).header("Content-Type", "application/json").body(JSON.toJSONString(paramMap)).execute().body();
            log.info("【新鼎鑫金服】获取token结束【result】{}", result);


            JSONObject resultObject = JSON.parseObject(result);
            String orsucess = resultObject.getString("orsuccess");
            if (StrUtil.equals(String.valueOf(orsucess), "1")) {
                token = resultObject.getString("token");
                stringRedisTemplate.opsForValue().set(redisKey, token, TOKEN_EXPIRY_MINUTES, TimeUnit.MINUTES);
            }
        }
        return token;
    }


    private String getUserInfo(MemberSourceInfo memberSourceInfo){
        String sex = ObjectUtil.equals(memberSourceInfo.getSex(), 1)?"男":"女";
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder
                .append("平台名称：臻享分期" ).append("；")
                .append("城市：" + memberSourceInfo.getCity()).append("；")
                .append("年龄：" + memberSourceInfo.getAge()).append("；")
                .append("性别：" + sex).append("；")
                .append("房产：").append(memberCommonService.queryDictInfoByValue(memberSourceInfo.getHouse()).getName()).append("；")
                .append("车产：").append(memberCommonService.queryDictInfoByValue(memberSourceInfo.getCar()).getName()).append("；")
                .append("公积金：").append(memberCommonService.queryDictInfoByValue(memberSourceInfo.getGjj()).getName()).append("；")
                .append("逾期情况：").append(memberCommonService.queryDictInfoByValue(memberSourceInfo.getYuqi()).getName()).append("；")
                .append("社保：").append(memberCommonService.queryDictInfoByValue(memberSourceInfo.getShebao()).getName()).append("；")
                .append("保险：").append(memberCommonService.queryDictInfoByValue(memberSourceInfo.getBaoxian()).getName()).append("；")
                .append("芝麻分：").append(memberCommonService.queryDictInfoByValue(memberSourceInfo.getZhima()).getName()).append("；")
                .append("白条：").append(memberCommonService.queryDictInfoByValue(memberSourceInfo.getBaitiao()).getName()).append("；")
                .append("花呗：").append(memberCommonService.queryDictInfoByValue(memberSourceInfo.getHuabei()).getName()).append("；")
                .append("职业：").append(memberCommonService.queryDictInfoByValue(memberSourceInfo.getGongzuo()).getName()).append("；")
        ;
        return stringBuilder.toString();
    }

    public static void main(String[] args) {

        String requestUrl = "http://dxapi.51xxzhbei.cn/openapi/GetAccessToken.aspx";

        Map<String, String> paramMap = new HashMap<>();
        paramMap.put("accessID", "1725259358085");
        paramMap.put("accessKey", "cda1db22000743b7bc0b8c9693ee5e5e");

        log.info("【新鼎鑫金服】获取token【queryUrl】{}【paramMap】{}", requestUrl, JSON.toJSONString(paramMap));
        String result = HttpUtil.createPost(requestUrl).header("Content-Type", "application/json").body(JSON.toJSONString(paramMap)).execute().body();
        log.info("【新鼎鑫金服】获取token结束【result】{}", result);

        System.out.println(result);

        String token = "";


        JSONObject resultObject = JSON.parseObject(result);
        String orsucess = resultObject.getString("orsucess");
        if (StrUtil.equals(String.valueOf(orsucess), "1")) {
            token = resultObject.getString("token");
        }
        System.out.println(token);

    }

}
